package com.whmskj.xjlhsc.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import com.whmskj.xjlhsc.config.properties.FileProperties;
import com.whmskj.xjlhsc.controller.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.time.LocalDate;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @BelongsProject: XJLHSC
 * @BelongsPackage: com.whmskj.xjlhsc.controller
 * @Author: lk
 * @CreateTime: 2025-06-13
 * @Description: 文件上传
 * @Version: 1.0
 */
@RestController
@RequestMapping("/api/file")
@EnableConfigurationProperties(FileProperties.class)
@SaIgnore
public class FileController {

    @Autowired
    private FileProperties fileProperties;

    @PostMapping("/upload")
    public Result upload(@RequestParam MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        assert originalFilename != null;
        String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
        if (!fileProperties.getAllowedExtensions().contains(ext.replace(".", "")))
            return Result.error("不允许上传该文件类型");
        if (file.getSize() > fileProperties.getMaxFileSize()) return Result.error("文件过大");
        String fileName = System.currentTimeMillis() + ext;
        String dayPath = LocalDate.now().toString().replace("-", "");
        File desc = new File(fileProperties.getUploadFolder() + dayPath, fileName);
        try {
            FileUtil.writeFromStream(file.getInputStream(), desc);
        } catch (FileNotFoundException ex) {
            if (desc.getParentFile().mkdirs()) try {

                FileUtil.writeFromStream(file.getInputStream(), desc);

            } catch (IOException e) {

                throw new RuntimeException(e);
            }
        } catch (IOException e) {

            return Result.error("上传失败");
        }
        Map<String, String> resp = new LinkedHashMap<>();
        resp.put("url", fileProperties.getBaseUrl() + dayPath + '/' + fileName);
        resp.put("name", originalFilename);
        resp.put("extName", ext.replace(".", ""));
        return Result.success(resp);
    }
}
